package com.gomro.galaxy.foundation.bi.engine.analysis;

import cn.gomro.cloud.core.common.utils.DateUtils;
import cn.gomro.cloud.core.common.utils.EncryptUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gomro.galaxy.core.batch.ElasticSearchClzItemReader;
import com.gomro.galaxy.core.batch.ElasticSearchClzItemWriter;
import com.gomro.galaxy.core.commons.elastic.ElasticSearchRest;
import com.gomro.galaxy.foundation.bi.domain.Constants;
import com.gomro.galaxy.foundation.bi.domain.enumerater.VendorType;
import com.gomro.galaxy.foundation.bi.domain.event.ProtocolVendorQuotationEvent;
import com.gomro.galaxy.foundation.bi.domain.model.AcquireMember;
import com.gomro.galaxy.foundation.bi.domain.model.AcquireOrganization;
import com.gomro.galaxy.foundation.bi.domain.model.AcquirePurchaseGoods;
import com.gomro.galaxy.foundation.bi.domain.model.AcquireQuotationGoods;
import com.gomro.galaxy.foundation.bi.domain.model.analysis.WorkbenchVendorQuotation;
import com.gomro.galaxy.foundation.bi.engine.AnalysisLastTime;
import com.gomro.galaxy.foundation.bi.engine.model.AnalysisCache;
import com.gomro.galaxy.foundation.bi.engine.query.MemberQuery;
import com.gomro.galaxy.foundation.bi.engine.query.QuotationGoodsQuery;
import com.gomro.galaxy.foundation.bi.engine.util.BoolQueryBuilders;
import com.gomro.galaxy.foundation.bi.engine.util.EngineUtils;
import com.gomro.galaxy.foundation.bi.exception.BiException;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.util.CollectionUtils;

import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import static com.gomro.galaxy.foundation.bi.domain.model.analysis.WorkbenchVendorQuotation.ProtocolJobSuffix;
import static com.gomro.galaxy.foundation.bi.engine.util.EngineUtils.MAX_BATCH_NUM;

/**
 * 协议供应商报价导出
 */
@Slf4j
@Configuration
public class ProtocolVendorQuotationJob {
    private static final String BiAnalysisLastName = Constants.BiDataMartIndexPrefix + AnalysisLastTime.TableName;
    private static final String WorkbenchVendorQuotationLastName = WorkbenchVendorQuotation.TableName + ProtocolJobSuffix;
    private static final String BiWarehouseMemberName = Constants.BiWarehouseIndexPrefix + AcquireMember.TableName;
    private static final String BiWarehouseQuotationGoodsName = Constants.BiWarehouseIndexPrefix + AcquireQuotationGoods.TableName;
    private static final String BiDataMartName = Constants.BiDataMartIndexPrefix + WorkbenchVendorQuotation.TableName;
    private static final String JobName = Constants.JobBeanNamePrefix + WorkbenchVendorQuotation.TableName + ProtocolJobSuffix;
    private static final String StepName1 = Constants.StepBeanNamePrefix + WorkbenchVendorQuotation.TableName + ProtocolJobSuffix + 1;
    private static final String StepName2 = Constants.StepBeanNamePrefix + WorkbenchVendorQuotation.TableName + ProtocolJobSuffix + 2;
    private static final String StepName3 = Constants.StepBeanNamePrefix + WorkbenchVendorQuotation.TableName + ProtocolJobSuffix + 3;
    private static final String StepName4 = Constants.StepBeanNamePrefix + WorkbenchVendorQuotation.TableName + ProtocolJobSuffix + 4;

    private static final String ReaderName1 = Constants.ReaderBeanNamePrefix + WorkbenchVendorQuotation.TableName + ProtocolJobSuffix + 1;
    private static final String ReaderName2 = Constants.ReaderBeanNamePrefix + WorkbenchVendorQuotation.TableName + ProtocolJobSuffix + 2;
    private static final String WriterName1 = Constants.WriterBeanNamePrefix + WorkbenchVendorQuotation.TableName + ProtocolJobSuffix + 1;
    private static final String WriterName2 = Constants.WriterBeanNamePrefix + WorkbenchVendorQuotation.TableName + ProtocolJobSuffix + 2;
    private static final String ProcessName4 = Constants.ProcessBeanNamePrefix + WorkbenchVendorQuotation.TableName + ProtocolJobSuffix + 4;

    private ApplicationEventPublisher applicationEventPublisher;
    private BusProperties busProperties;
    private JobBuilderFactory jobBuilderFactory;
    private StepBuilderFactory stepBuilderFactory;
    private ElasticSearchRest rest;
    private RestHighLevelClient client;
    private ObjectMapper mapper;
    private AnalysisCache<WorkbenchVendorQuotation> cache = new AnalysisCache<>();

    public ProtocolVendorQuotationJob(ApplicationEventPublisher applicationEventPublisher, BusProperties busProperties, JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, RestHighLevelClient client, ObjectMapper mapper) {
        this.applicationEventPublisher = applicationEventPublisher;
        this.busProperties = busProperties;
        this.jobBuilderFactory = jobBuilderFactory;
        this.stepBuilderFactory = stepBuilderFactory;
        this.client = client;
        this.mapper = mapper;
        this.rest = new ElasticSearchRest(client, mapper);
    }

    private JobExecutionListener jobExecutionListener = new JobExecutionListener() {

        @Override
        public void beforeJob(@NonNull JobExecution jobExecution) {

            ElasticSearchRest rest = new ElasticSearchRest(client, mapper);

            // 初始化数据索引
            if (!rest.indexExists(BiDataMartName)) {

                rest.indexCreate(BiDataMartName);
                rest.indexMappingPut(BiDataMartName, "analysis/" + BiDataMartName + ".json", true);
                rest.indexFlush(BiDataMartName, null, null);
            }

            // 初始化最后更新时间索引
            if (!rest.indexExists(BiAnalysisLastName)) {

                rest.indexCreate(BiAnalysisLastName);
                rest.indexMappingPut(BiAnalysisLastName, "analysis/" + BiAnalysisLastName + ".json", true);
                rest.indexFlush(BiAnalysisLastName, null, null);
            }
        }

        @Override
        public void afterJob(@NonNull JobExecution jobExecution) {

            log.debug("last time ---> {}", DateUtils.dateToStr(cache.getLast()));
            if (Objects.nonNull(cache.getCache())) {
                log.debug("cache size -> {}", cache.getCache().size());
                cache.getCache().clear();
            }
            // 回写最后更新时间
            if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
                rest.documentCreate(BiAnalysisLastName, WorkbenchVendorQuotationLastName, AnalysisLastTime.builder().id(WorkbenchVendorQuotationLastName).last(cache.getLast()).build());
                applicationEventPublisher.publishEvent(new ProtocolVendorQuotationEvent(cache.getLast()));
            }
        }
    };

    @Bean(ReaderName1)
    @StepScope
    public ElasticSearchClzItemReader<AcquireQuotationGoods> reader1() {
        List<Long> memberIds = getProtocolMemberIds();
        // 获取最后更新时间
        AnalysisLastTime analysisLastTime = rest.documentGet(BiAnalysisLastName, WorkbenchVendorQuotationLastName, AnalysisLastTime.class);
        Date start;
        if (analysisLastTime != null && analysisLastTime.getLast() != null) {
            start = analysisLastTime.getLast();
        } else {
            ElasticSearchRest.SearchResultClz<AcquireQuotationGoods> data = rest.searchAsClz(BiWarehouseQuotationGoodsName, ElasticSearchRest.Page.of(1, 1), null, Collections.singleton(SortBuilders.fieldSort("time").order(SortOrder.ASC)), null, AcquireQuotationGoods.class);
            if (Objects.isNull(data) || CollectionUtils.isEmpty(data.getData())) {
                throw new BiException("analysisLastTime init error");
            }
            start = Date.from(data.getData().get(0).getTime().atZone(ZoneId.systemDefault()).toInstant());
        }
        cache.setLast(start);
        QuotationGoodsQuery.QuotationGoodsQueryBuilder builder = QuotationGoodsQuery.builder().memberIds(memberIds);
        Date endDate = EngineUtils.getEndDate(start, (date, date2) -> rest.searchCount(BiWarehouseQuotationGoodsName,
                BoolQueryBuilders.quotationGoods(builder.start(date).end(date2).build())));
        if (Objects.nonNull(endDate)) {
            cache.setLast(endDate);
        } else {
            endDate = new Date();
            cache.setLast(endDate);
        }

        //初始化缓存, 不能并行任务
        if (Objects.isNull(cache.getCache())) {
            cache.setCache(new HashMap<>());
        }
        BoolQueryBuilder boolQueryBuilder = BoolQueryBuilders.quotationGoods(builder.start(start).end(endDate).build());
        long count = rest.searchCount(BiWarehouseQuotationGoodsName, boolQueryBuilder);
        log.debug("查询日期 -> {} count -> {}", DateUtils.dateToStr(cache.getLast(), DateUtils.FORMAT_PATTERN_DATE), count);
        ElasticSearchClzItemReader<AcquireQuotationGoods> reader = new ElasticSearchClzItemReader<>(client, mapper, BiWarehouseQuotationGoodsName,
                MAX_BATCH_NUM, boolQueryBuilder, Collections.singleton(SortBuilders.fieldSort("id").order(SortOrder.ASC)), AcquireQuotationGoods.class);
        reader.setName(ReaderName1);
        return reader;
    }

    private List<Long> getProtocolMemberIds() {
        MemberQuery query = MemberQuery.builder().protocolAccount(true).del(false).build();
        BoolQueryBuilder queryBuilder = BoolQueryBuilders.member(query);
        long memberCount = rest.searchCount(BiWarehouseMemberName, queryBuilder);
        ElasticSearchRest.SearchResultClz<AcquireMember> memberData = rest.searchAsClz(BiWarehouseMemberName,
                ElasticSearchRest.Page.of(1, (int) memberCount), queryBuilder, null, null, AcquireMember.class);
        if (Objects.nonNull(memberData) && !CollectionUtils.isEmpty(memberData.getData())) {
            return memberData.getData().stream().map(AcquireMember::getId).collect(Collectors.toList());
        }
        return Collections.singletonList(0L);
    }

    @Bean(WriterName1)
    public ItemWriter<WorkbenchVendorQuotation> writer1(){
        return list -> list.forEach(e -> cache.getCache().put(e.getId(), e));
    }

    @Bean(ReaderName2)
    @StepScope
    public ItemReader<WorkbenchVendorQuotation> reader2() {
        return EngineUtils.createCacheReader(cache.getCache());
    }

    @Bean(WriterName2)
    public ElasticSearchClzItemWriter<WorkbenchVendorQuotation> writer2() {

        return new ElasticSearchClzItemWriter<>(client, mapper, BiDataMartName);
    }

    @Bean(ProcessName4)
    public ItemProcessor<WorkbenchVendorQuotation, WorkbenchVendorQuotation> processor4() {
        return workbenchVendorQuotation -> {
            String id = EncryptUtils.MD5_32(workbenchVendorQuotation.getTime().toString() + VendorType.PROTOCOL.name() + workbenchVendorQuotation.getQuotationGoodsId());
            workbenchVendorQuotation.setId(id);
            workbenchVendorQuotation.setType(VendorType.PROTOCOL);
            return workbenchVendorQuotation;
        };
    }


    @Bean(JobName)
    public Job job(@Qualifier(StepName1) Step step1, @Qualifier(StepName2) Step step2,
                   @Qualifier(StepName3) Step step3,@Qualifier(StepName4) Step step4) {

        return jobBuilderFactory.get(JobName)
                .incrementer(new RunIdIncrementer())
                .start(step1)
                .next(step2)
                .next(step3)
                .next(step4)
                .listener(jobExecutionListener)
                .build();
    }

    @Bean(StepName1)
    public Step step1(@Qualifier(InternalVendorQuotationJob.ProcessName1) ItemProcessor<AcquireQuotationGoods, WorkbenchVendorQuotation> processor) {

        return stepBuilderFactory.get(StepName1)
                .<AcquireQuotationGoods, WorkbenchVendorQuotation>chunk(MAX_BATCH_NUM)
                .reader(reader1())
                .processor(processor)
                .writer(writer1())
                .build();
    }

    @Bean(StepName2)
    public Step step2(@Qualifier(InternalVendorQuotationJob.ProcessName2) ItemProcessor<WorkbenchVendorQuotation, WorkbenchVendorQuotation> processor) {

        return stepBuilderFactory.get(StepName2)
                .<WorkbenchVendorQuotation, WorkbenchVendorQuotation>chunk(MAX_BATCH_NUM)
                .reader(reader2())
                .processor(processor)
                .writer(writer1())
                .build();
    }

    @Bean(StepName3)
    public Step step3(@Qualifier(InternalVendorQuotationJob.ProcessName3) ItemProcessor<WorkbenchVendorQuotation, WorkbenchVendorQuotation> processor) {

        return stepBuilderFactory.get(StepName3)
                .<WorkbenchVendorQuotation, WorkbenchVendorQuotation>chunk(MAX_BATCH_NUM)
                .reader(reader2())
                .processor(processor)
                .writer(writer1())
                .build();
    }


    @Bean(StepName4)
    public Step step4() {

        return stepBuilderFactory.get(StepName4)
                .<WorkbenchVendorQuotation, WorkbenchVendorQuotation>chunk(MAX_BATCH_NUM)
                .reader(reader2())
                .processor(processor4())
                .writer(writer2())
                .build();
    }


}
